package com.itheima.web.servlet;


import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //设置请求编码
            req.setCharacterEncoding("UTF-8");
            //获取所有请求参数的集合
            Map<String, String[]> map = req.getParameterMap();
            //将集合封装到user对象
            User u=new User();
            BeanUtils.populate(u,map);
            //让service去检查登录账户信息
            UserService service=new UserServiceImpl();
            User existUser=service.login(u);
            //判断登录用户信息给出对应的反馈
            if (existUser==null){
                //账户信息不对就使用请求域保存错误信息
                req.setAttribute("msg","用户名或者密码错误！");
                //请求转发回到登录页，并显示错误信息
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }else {
                //账户信息存在则登录成功,将登录信息保存到Session域再重定向回到首页
                req.getSession().setAttribute("user",existUser);
                resp.sendRedirect(req.getContextPath()+"/index.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
